package thread;

import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 定时器
 */
class myTask {
    private Runnable runnable;   //描述任务
    private long time;    //时间
    public myTask(Runnable runnable,long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis()+delay;
    }
    //执行任务
    public void run() {
        runnable.run();
    }
    //拿到任务需要执行的时间
    public long getTime(){
        return time;
    }
}
class MyTimer{
    //定时器内部要能够存放多个任务（数据结构存储）优先级阻塞队列
    private PriorityBlockingQueue<myTask> queue = new PriorityBlockingQueue<myTask>(10, new Comparator<myTask>() {
        @Override
        public int compare(myTask o1, myTask o2) {
            return (int)(o1.getTime()-o2.getTime());
        }
    });
    //创建任务，放到优先级阻塞队列中
    public void schedule(Runnable runnable,long delay) {
        myTask task = new myTask(runnable,delay);
        queue.put(task);
        //放入一个就需要唤醒，防止比之前的任务都先执行
        synchronized (locker) {
            locker.notify();
        }
    }
    private Object locker = new Object();
    public MyTimer() {
        Thread t = new Thread(()->{
           while (true) {
               try {
                   //弄一个线程持续检查
                   myTask task = queue.take();
                   long time = System.currentTimeMillis();
                   if(time < task.getTime()) {
                       queue.put(task);
                       synchronized (locker) {
                           //进入阻塞，可以中途唤醒，如果加入任务比最先需要执行的任务还早，就唤醒
                           locker.wait(task.getTime()-time);
                       }
                   }else {
                       task.run();
                   }
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        t.start();
    }
}
public class  Demo11 {
    public static void main(String[] args) {
        MyTimer myTimer = new MyTimer();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("这是3秒后，hello,我的定时器");
            }
        },3000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("5秒后");
            }
        },5000);
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("7秒后");
            }
        },7000);
        System.out.println("我的定时器来啦");
    }
}
